import React, { PureComponent } from 'react';
import moment from 'moment';
import {
  Row, Col, Form, Input, Select, Icon, Dropdown, InputNumber, DatePicker, Modal, message,
  Table, Alert, Badge, Divider, Card, Menu, Button, Popconfirm, Collapse, Carousel, Tree, Switch,
  List, Avatar, Tooltip, Tabs
} from 'antd';
import SyCarouselImageModalComponent from '../SyCarouselImageModalComponent'
import styles from './index.less';
import DescriptionList from 'components/DescriptionList';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { hasAuthority } from '../../utils/authority';
const { Description } = DescriptionList;
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const Panel = Collapse.Panel;
const TreeNode = Tree.TreeNode;
const TabPane = Tabs.TabPane;

function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}

export const SyOrderTableBasicFormComponent = Form.create()(
  (props) => {
    const _wrapperCol = {
      xs: { span: 24 },
      sm: { span: 24 },
      md: { span: 24 },
    };

    const { form, formItems, selectItems, needInitValue, editedEntity, wrapperCol, onPressEnter, operatorLoading, renderAppend } = props;
    const { getFieldDecorator } = form;

    const handleSelectItem = (selectOption) => {
      let result = [{ key: "请选择", name: '--请选择--', value: null }];

      if (typeof selectOption === 'function') {
        let option = selectOption(form.getFieldsValue());
        for (let op of option) {
          result.push(op);
        }
        return result;
      }

      if (Array.isArray(selectOption)) {
        for (let op of selectOption) {
          result.push(op);
        }
        return result;
      }

      if (selectItems[selectOption.itemName]) {
        result.push(
          ...selectItems[selectOption.itemName].map(
            item => {
              const name = typeof selectOption.name === 'function' ? selectOption.name(item) : item[selectOption.name];
              const value = selectOption.value ? item[selectOption.value] : JSON.stringify(item);
              const key = selectOption.value ? item[selectOption.value] : item.id;

              return {
                key: key,
                name: name,
                value: value,
              };
            }
          )
        );
      }
      return result;
    }

    const handleMultipleSelectItem = (selectOption) => {
      let result = [];
      if (selectItems[selectOption.itemName]) {
        result.push(
          ...selectItems[selectOption.itemName].map(
            item => {
              const name = typeof selectOption.name === 'function' ? selectOption.name(item) : item[selectOption.name];
              const value = selectOption.value ? item[selectOption.value] : JSON.stringify(item);
              const key = selectOption.value ? item[selectOption.value] : item.id;

              return {
                key: key,
                name: name,
                value: value,
              };
            }
          )
        );
      }
      return result;
    }

    const handleInitValue = (formItem) => {
      if (formItem.initValue && typeof formItem.initValue === 'function') {
        return formItem.initValue(form.getFieldsValue());
      }

      if (formItem.initValue) {
        return formItem.initValue;
      } else if (needInitValue) {
        return handleNameWithDot(editedEntity, formItem);
      } else {
        if (formItem.type == 'multiple') {
          return [];
        }
        return null;
      }

    }

    const handleNameWithDot = (value, formItem) => {
      let arr = formItem.name.split(".");
      for (let i in arr) {
        value = value[arr[i]];
        if (value == undefined || value == null) {
          return null;
        }
      }



      if (Array.isArray(value)) {
        const arr = selectItems[formItem.selectOption.itemName].filter(data => value.filter(v => v.id == data.id).length > 0);
        return arr.map(data => JSON.stringify(data));
      } else if (typeof value === 'object') {
        return JSON.stringify(selectItems[formItem.selectOption.itemName].filter(data => data.id == value.id)[0]);
      } else if (formItem.type == 'dateTime') {
        return moment(value);
      } else {
        return value;
      }

    }

    const renderFormItem = (formItem) => {
      let itemComponent = null;

      formItem.type = typeof formItem.type == 'function' ? formItem.type() : formItem.type;

      formItem.rendered = formItem.rendered == undefined ? true
        :
        (typeof formItem.rendered == 'function' ? formItem.rendered() : formItem.rendered);

      if (!formItem.rendered) {
        return;
      }

      switch (formItem.type) {
        case 'readOnly':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                <span className="ant-form-text" >{handleInitValue(formItem)}</span>
              </FormItem>
            </Col>
          );
          break;
        case 'string':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })(<Input placeholder={formItem.placeholder} onChange={formItem.onChange} onPressEnter={onPressEnter} />)
                }
              </FormItem>
            </Col>
          );
          break;
        case 'longString':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })(<TextArea placeholder={formItem.placeholder} rows={formItem.rows ? formItem.rows : 3} onChange={formItem.onChange} onPressEnter={onPressEnter} />)
                }
                {formItem.append}
              </FormItem>
            </Col>
          );
          break;
        case 'number':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })
                  (
                  // <InputNumber placeholder={formItem.placeholder} onChange={formItem.onChange} />
                  <Input type="number" lang="en" placeholder={formItem.placeholder} onPressEnter={onPressEnter} />
                  // <Input
                  //   onKeyDown={(e) => {
                  //     console.log('-----1'); console.log(e.target.value);
                  //     if (e.keyCode == 110 || e.keyCode == 190) {
                  //       if (e.target.value.indexOf('.') > -1) {
                  //         e.preventDefault();
                  //       }
                  //     }
                  //     if (e.keyCode < 96 || e.keyCode > 105 && e.keyCode != 110 && e.keyCode != 190) {
                  //       e.preventDefault();
                  //     }
                  //   }}
                  //   // onKeyPress={(e) => { console.log('-----0'); console.log(e.target.value); e.target.value = ''; }}
                  //   // onKeyUp={(e) => { console.log('-----2'); console.log(e.target.value); e.target.value = ''; }}
                  // />
                  )
                }
              </FormItem>
            </Col>
          );
          break;
        case 'boolean':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  valuePropName: 'checked',
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })(<Switch checkedChildren="是" unCheckedChildren="否" onChange={formItem.onChange} />)
                }
              </FormItem>
            </Col>
          );
          break;
        case 'select':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })(
                  <Select
                    showSearch
                    placeholder={formItem.placeholder}
                    optionFilterProp="children"
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={formItem.onChange}
                  >
                    {
                      handleSelectItem(formItem.selectOption).map(
                        option => (<Select.Option key={option.value} value={option.value} >{option.name}</Select.Option>)
                      )
                    }
                  </Select>
                )
                }
              </FormItem>
            </Col>
          );
          break;
        case 'multiple':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })(
                  <Select
                    placeholder={formItem.placeholder}
                    mode="multiple"
                    optionFilterProp="children"
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={formItem.onChange}
                  >
                    {
                      handleMultipleSelectItem(formItem.selectOption).map(
                        option => (<Select.Option key={option.key} value={option.value}>{option.name}</Select.Option>)
                      )
                    }
                  </Select>
                )
                }
              </FormItem>
            </Col>
          );
          break;
        case 'dateTime':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })(<DatePicker
                  showTime={!!formItem.showTime}
                  format={formItem.format ? formItem.format : 'YYYY-MM-DD'}
                  placeholder={formItem.placeholder}
                  onChange={formItem.onChange}
                />)
                }
              </FormItem>
            </Col>
          );
          break;
        case 'rangerTime':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                  initialValue: handleInitValue(formItem),
                  rules: formItem.rules,
                })(<RangePicker
                  ranges={{
                    近7天: [moment().subtract(7, 'days'), moment()],
                    近14天: [moment().subtract(14, 'days'), moment()],
                    近30天: [moment().subtract(30, 'days'), moment()],
                  }}
                  format={formItem.format ? formItem.format : 'YYYY-MM-DD'}
                  placeholder={formItem.placeholder}
                  onChange={formItem.onChange}
                />)
                }
              </FormItem>
            </Col>
          );
          break;
        case 'ranger':
          itemComponent = (
            <Col {...wrapperCol ? { ...wrapperCol } : { ..._wrapperCol }} key={formItem.name}  >
              <FormItem label={formItem.label}>
                {getFieldDecorator(formItem.name, {
                })(<RangePicker
                  format={formItem.format ? formItem.format : 'YYYY-MM-DD'}
                  onChange={formItem.onChange}
                />)
                }
              </FormItem>
            </Col>
          );
          break;
        default:
          break;
      }

      return itemComponent;
    }

    return (
      <div>
        <Form layout="inline" >
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            {
              formItems.map(
                formItem => renderFormItem(formItem)
              )
            }
          </Row>
        </Form>
        {renderAppend && renderAppend()}
      </div>
    );
  }
);

const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
class SyOrderTableComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      expandForm: false,
      selectedRows: [],
      selectedRowKeys: [],
      searchFormValues: {},
      editedEntity: {},
      searchFormItem: [],
      tableColumns: [],
      tableScroll: { x: 1200, y: 800 },
      baseModel: '',
      queryUrl: '',
      selectItems: {},
      modalImageValues: [],
      modalTitle: '',
      modalWidth: 800,
      currentFormRef: {},
      currentFormSubmit: () => { },
      currentRenderForm: () => { },
      currentModalFootButton: [],
      currentOnCancelEvent: () => { },
      initSortion: { sortField: 'id', sortOrder: 'desc', },
      initPagination: { pageSize: 10, current: 1, },
      initCriteriaQuery: {},
      needTableStatistics: false,
      // totalCallNo: 0,
      entityStatus: [],
      statusQuery: {},
      statusField: '',
      expandedRowRender: null,
      showTableHeader: true,
      defaultExpandAllRows: false,

      needTotalList: 0,
      //订单个数, 订单总额
      orderNum: 0,
      orderAmount: 0,
    };
  }

  // 缺省
  _operator = [];
  _operatorBefore = [];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: this.state.baseModel + (this.state.fetchUrl ? this.state.fetchUrl : '/fetch'),
      payload: {
        ...this.state.initPagination,
        ...this.state.initSortion,
        ...this.state.initCriteriaQuery,
        ...this.state.statusQuery,
        queryUrl: this.state.queryUrl,
      }
    });

  }

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  }

  handleTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { searchFormValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...pagination,
      ...this.state.initSortion,
      ...this.state.initCriteriaQuery,
      ...this.state.statusQuery,
      ...searchFormValues,
      ...filters,
      queryUrl: this.state.queryUrl,
    };

    if (sorter.field) {
      switch(sorter.field) {
        case 'products[0].backProduct.createTime':
          //patch for page refundOrder.js due to API param
          params.column = 'create_time';
          params.columnStatus = sorter.order == 'ascend' ? 'ASC' : ( sorter.order == 'descend' ? 'DESC' : sorter.order );
          params.sortOrder = '';
          break;
        default:
          params.sortField = sorter.field;
          params.sortOrder = sorter.order.replace("end", "");
          break;
      }
    }

    dispatch({
      type: this.state.baseModel + (this.state.fetchUrl ? this.state.fetchUrl : '/fetch'),
      payload: params,
    });
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    if (selectedRows.length > 0) {
      this.setState({ editedEntity: selectedRows[0] });
    } else {
      this.setState({ editedEntity: {} });
    }
    this.setState({ selectedRowKeys, selectedRows });
    //统计已选择的订单数量和总额
    let count = {
      number: selectedRows.length,
      amount: 0,
    };
    if (selectedRows[0] && selectedRows[0].withdrawAmount) {
      selectedRows.forEach((val, index, arr) => {
        count.amount += val.withdrawAmount
      });
    } else if (selectedRows[0] && selectedRows[0].loanAmount) {
      selectedRows.forEach((val, index, arr) => {
        count.amount += val.loanAmount
      });
    } else {}
    this.setState({
      orderNum: count.number,
      orderAmount: count.amount.toFixed(2),
    })
  }

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  }


  isJSON = (value) => {
    if (typeof value == 'string') {
      try {
        let obj = JSON.parse(value);
        return obj;
      } catch (e) {
        return null;
      }
    }
    return null;
  }

  // form表单转换json字符串为object
  conventFormValue = (fieldValue, formItems) => {
    for (let variable in fieldValue) {

      if (fieldValue[variable]) {
        const formItem = formItems.filter(data => data.name === variable)[0];

        if (formItem.type == 'dateTime') {
          fieldValue[variable] = fieldValue[variable].format(formItem.format ? formItem.format : 'YYYY-MM-DD');
        }

        if (formItem.selectOption && !formItem.selectOption.value) {
          if (formItem.type == 'select') {
            // fieldValue[variable] = JSON.parse(fieldValue[variable]);
          } else if (formItem.type == 'multiple') {
            let arr = [];
            for (let v of fieldValue[variable]) {
              arr.push(JSON.parse(v));
            }
            fieldValue[variable] = arr;
          }
        }
      }
    }

    return fieldValue;
  }

  /********************************* 处理form *********************************/

  // searchForm
  renderSearchForm = () => {
    const { form, modelState: { selectItems } } = this.props;
    const { getFieldDecorator } = form;
    const { searchFormItem, searchPanelUnCollapse } = this.state;
    return (
      <Collapse bordered={false} defaultActiveKey={searchPanelUnCollapse ? ['0'] : []} >
        <Panel header="查询条件" key="0"  >
          <SyOrderTableBasicFormComponent
            ref={this.saveSearchFormRef}
            formItems={searchFormItem}
            selectItems={selectItems}
            wrapperCol={{ md: 7, sm: 14 }}
            onPressEnter={this.handleSearchEvent}
          >
          </SyOrderTableBasicFormComponent >
          <Row>
            <Col >
              <span className={styles.submitButtons}>
                <Button style={{ marginLeft: 16, float: 'right' }} icon="reload" onClick={this.handleSearchRest}>重置</Button>
                <Button style={{ float: 'right' }} type="primary" icon="search" onClick={this.handleSearchEvent}>查询</Button>
              </span>
            </Col>
          </Row>
        </Panel>
      </Collapse>

    );
  }

  saveSearchFormRef = (form) => {
    this.searchForm = form;
  }

  handleSearchEvent = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    const form = this.searchForm;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...this.conventFormValue(fieldsValue, this.state.searchFormItem),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      //rangeType_Date => [startDate.format, endDate.format];
      if (values.rangeType_Date) {
        [values.startDate, values.endDate] = [values.rangeType_Date[0].format('YYYY-MM-DD HH:mm:ss'), values.rangeType_Date[1].format('YYYY-MM-DD HH:mm:ss')];
        values.refundOrderDateRange = '';
      }
      //deal specially value
      if(values.startDate || values.endDate){
        if(values.startDate){
          values.startDate = moment(values.startDate).format('YYYY-MM-DD HH:mm:ss')
        }
        if(values.endDate){
          values.endDate = moment(values.endDate).format('YYYY-MM-DD HH:mm:ss')
        }
      }
      if(this.state.initType=='ranger'){
        values.lendStartDate = fieldsValue.lendTime_n ? moment(fieldsValue.lendTime_n[0]).format('YYYY-MM-DD'): null;
        values.lendEndDate = fieldsValue.lendTime_n ? moment(fieldsValue.lendTime_n[1]).format('YYYY-MM-DD'): null;
        values.repayStartDate = fieldsValue.repayTime_n ? moment(fieldsValue.repayTime_n[0]).format('YYYY-MM-DD'): null;
        values.repayEndDate = fieldsValue.repayTime_n ? moment(fieldsValue.repayTime_n[1]).format('YYYY-MM-DD'): null;
        values.startDate = fieldsValue.shouldTime_n ? moment(fieldsValue.shouldTime_n[0]).format('YYYY-MM-DD'): null;
        values.endDate = fieldsValue.shouldTime_n ? moment(fieldsValue.shouldTime_n[1]).format('YYYY-MM-DD'): null;
        delete values.lendTime_n;
        delete values.repayTime_n;
        delete values.shouldTime_n;
      }
      this.setState({
        searchFormValues: values,
      });
      console.log(values)
      dispatch({
        type: this.state.baseModel + (this.state.fetchUrl ? this.state.fetchUrl : '/fetch'),
        payload: {
          ...this.state.initPagination,
          ...this.state.initSortion,
          ...this.state.initCriteriaQuery,
          ...this.state.statusQuery,
          ...values,
          queryUrl: this.state.queryUrl,
        },
      });
    });
  }

  handleSearchRest = (e) => {
    e.preventDefault();
    const form = this.searchForm;
    form.resetFields();
  }

  // simpleAddForm
  renderSimpleAddForm = () => {
    const { form, modelState: { selectItems } } = this.props;
    const { getFieldDecorator } = form;
    const { simpleAddFormItem } = this.state;
    return (
      <SyOrderTableBasicFormComponent
        ref={this.saveSimpleAddFormRef}
        formItems={simpleAddFormItem}
        selectItems={selectItems}
      >
      </SyOrderTableBasicFormComponent>
    );
  }

  saveSimpleAddFormRef = (form) => {
    this.simpleAddForm = form;
  }

  // add
  handleSimpleAddEvent = () => {
    const { dispatch } = this.props;
    const form = this.simpleAddForm;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (this.state.beforeAdd) {
        if (!this.state.beforeAdd(form, fieldsValue)) {
          return;
        };
      }


      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      dispatch({
        type: this.state.baseModel + '/add',
        payload: { ...this.conventFormValue(fieldsValue, this.state.simpleAddFormItem) },
        callback: (code, msg) => {
          if (code == 200) {
            message.success(msg);
            this.resetCurrentForm();
            dispatch({
              type: this.state.baseModel + (this.state.fetchUrl ? this.state.fetchUrl : '/fetch'),
              payload: {
                ...this.state.initPagination,
                ...this.state.initSortion,
                ...this.state.initCriteriaQuery,
                ...this.state.statusQuery,
                queryUrl: this.state.queryUrl,
              }
            });
          } else {
            message.error(msg);
          }
        },
      });
    });
  }

  // simpleEditForm
  renderSimpleEditForm = () => {
    const { form, modelState: { selectItems, operatorLoading } } = this.props;
    const { getFieldDecorator } = form;
    const { simpleEditFormItem, editedEntity } = this.state;
    return (
      <SyOrderTableBasicFormComponent
        ref={this.saveSimpleEditFormRef}
        formItems={simpleEditFormItem}
        selectItems={selectItems}
        needInitValue={true}
        editedEntity={editedEntity}
        operatorLoading={operatorLoading}
      >
      </SyOrderTableBasicFormComponent>
    );
  }

  saveSimpleEditFormRef = (form) => {
    this.simpleEditForm = form;
  }

  handleSimpleEditEvent = () => {
    const { dispatch } = this.props;
    const form = this.simpleEditForm;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      dispatch({
        type: this.state.baseModel + '/edit',
        payload: {
          ...this.state.editedEntity,
          ...this.conventFormValue(fieldsValue, this.state.simpleEditFormItem),
        },
        callback: (code, msg) => {
          if (code == 200) {
            message.success(msg);

            // 服务器端验证
            // form.setFields({
            //   userName: {
            //     value: fieldsValue.userName,
            //     errors: [new Error('aa'), { message: 'bb' },]
            //   }
            // });

            this.resetCurrentForm();
            dispatch({
              type: this.state.baseModel + (this.state.fetchUrl ? this.state.fetchUrl : '/fetch'),
              payload: {
                ...this.state.initPagination,
                ...this.state.initSortion,
                ...this.state.initCriteriaQuery,
                ...this.state.statusQuery,
                queryUrl: this.state.queryUrl,
              }
            });

          } else {
            message.error(msg);
          }
        },
      });
    });
  }

  // delete
  handleDeleteEvent = (editedEntity) => {
    const { dispatch } = this.props;
    dispatch({
      type: this.state.baseModel + '/delete',
      payload: editedEntity ? [editedEntity] : this.state.selectedRows,

      callback: (code, msg) => {
        if (code == 200) {
          message.success(msg);
          this.restSelectRows();
          dispatch({
            type: this.state.baseModel + (this.state.fetchUrl ? this.state.fetchUrl : '/fetch'),
            payload: {
              ...this.state.initPagination,
              ...this.state.initSortion,
              ...this.state.initCriteriaQuery,
              ...this.state.statusQuery,
              queryUrl: this.state.queryUrl,
            }
          });
        } else {
          message.error(msg);
        }
      },
    });
  }


  /********************************* basicOperator *********************************/
  // 清空当前selectRows
  restSelectRows = () => {
    this.setState({
      editedEntity: {},
      selectedRows: [],
      selectedRowKeys: [],
    });
  }

  // 清空当前state中的formRef、submit方法；将modal隐藏
  resetCurrentForm = () => {
    this.setState({
      currentFormRef: {},
      currentFormSubmit: () => { },
      currentRenderForm: () => { },
      currentOnCancelEvent: () => { },
      currentModalFootButton: [
        <Button key="cancel" onClick={() => this.handleOperator()}>
          取消
          </Button>,
        <Button key="ok" type="primary" loading={this.props.modelState.operatorLoading} onClick={this.handleModalSubmit}>
          确定
          </Button>,
      ],
      modalVisible: false,
    });
    this.restSelectRows();
  }

  handleModalSubmit = (e) => {
    e.preventDefault();
    this.state.currentFormSubmit();
  }


  // 处理操作
  // 处理modal是否显示，
  // 并且绑定当前formRef，formSubmit
  // 1.（需要modal的操作）flag为true：打开modal；并绑定当前formRef，formSubmit
  // //  * 2.（不需要modal的操作）flag为undefined或空：隐藏modal；并绑定当前formRef，formSubmit
  // 3.（隐藏modal）flag为undefined或空：隐藏modal；formRef，formSubmit为undefined 清空当前的绑定formRef，formSubmit
  handleOperator = (flag, title, formRef, submit, renderForm, initEntity, onClickEvent, onCancelEvent, modalFootButton, modalWidth) => {
    this.setState({
      modalVisible: !!flag,
      modalTitle: title ? title : '',
      modalWidth: modalWidth ? modalWidth : 800,
    });

    // 设置当前表单ref和提交方法
    if (formRef) {
      this.setState({
        currentFormRef: formRef,
      });
      formRef.resetFields();
    } else {
      this.setState({
        currentFormRef: {},
      });
    }
    if (submit) {
      this.setState({
        currentFormSubmit: submit,
      });
    } else {
      this.setState({
        currentFormSubmit: () => { },
      });
    }
    if (renderForm) {
      this.setState({
        currentRenderForm: renderForm,
      });
    } else {
      this.setState({
        currentRenderForm: () => { },
      });
    }
    if (initEntity) {
      this.setState({
        editedEntity: { ...this.state.editedEntity, ...initEntity },
      });
    }
    if (onCancelEvent) {
      this.setState({
        currentOnCancelEvent: onCancelEvent,
      });
    } else {
      this.setState({
        currentOnCancelEvent: () => { },
      });
    }

    if (modalFootButton) {
      this.setState({
        currentModalFootButton: modalFootButton,
      });
    } else {
      this.setState({
        currentModalFootButton: [
          <Button key="cancel" onClick={() => this.handleOperator()}>
            取消
          </Button>,
          <Button key="ok" type="primary" loading={this.props.modelState.operatorLoading} onClick={this.handleModalSubmit}>
            确定
          </Button>,
        ],
      });
    }



    if (onClickEvent && !!flag) {
      onClickEvent();
    }

    this.state.currentOnCancelEvent();

    if (!flag) {
      this.resetCurrentForm();
    }

  }


  /********************************* operator *********************************/
  _operator_index = 0;
  renderOperator = (operator) => {
    this._operator_index++;
    const { selectedRows } = this.state;

    if (operator.authority != undefined && operator.authority != null && !hasAuthority(operator.authority)) {
      return null;
    }

    let buttonConfig = {
      size: operator.size ? operator.size : 'default'
    }
    if (operator.buttonIcon != 'none') {
      buttonConfig.icon = operator.buttonIcon ? operator.buttonIcon : 'save'
    }

    return (
      <Button key={this._operator_index} className={styles.tableListBasicOperatorBtn}
              style={{marginRight:20}}
        {...buttonConfig}
        type={operator.buttonType ? operator.buttonType : ''}
        disabled={operator.buttonDisabled ?
          (operator.buttonDisabled == 'none' ?
            selectedRows.length <= 0
            :
            (operator.buttonDisabled == 'more' ?
              selectedRows.length != 1
              :
              selectedRows.length <= 0
            )
          )
          :
          selectedRows.length < 0}
        onClick={
          operator.needForm ?
            (() => this.handleOperator(true, operator.modalTitle, null, operator.handleEvent, operator.renderForm, null, operator.onClickEvent, null, null, operator.modalWidth))
            :
            (operator.needConfirm ?
              () => this.renderNeedConfirmOperatorModal(operator)
              :
              (operator.handleEvent ? operator.handleEvent : null))
        }

      >
        {operator.buttonLabel ? typeof operator.buttonLabel === 'function' ? operator.buttonLabel() : operator.buttonLabel : '操作'}
      </Button>
    )
  }

  renderNeedConfirmOperatorModal = (operator) => {
    Modal.confirm({
      ...operator,
      title: operator.confirmTitle,
      content: operator.confirmContent,
      okType: operator.okType,
      onOk: operator.handleEvent,
      onCancel: operator.handleCancel,
      okText: operator.okText ? operator.okText : '确认',
      cancelText: operator.cancelText ? operator.cancelText : '取消',
    });
  }

  onEntityStatusTabChange = (tabKey) => {
    const { dispatch } = this.props;
    const { searchFormValues } = this.state;

    tabKey = JSON.parse(tabKey);
    let statusQuery = {};
    statusQuery[this.state.statusField] = tabKey.value;

    this.setState({
      statusQuery: { ...statusQuery },
    });
    const params = {
      ...this.state.initSortion,
      ...this.state.initCriteriaQuery,
      ...statusQuery,
      ...searchFormValues,
      ...this.state.initPagination,
      queryUrl: this.state.queryUrl,
    };

    dispatch({
      type: this.state.baseModel + (this.state.fetchUrl ? this.state.fetchUrl : '/fetch'),
      payload: params,
    });
  }

  /********************************* render *********************************/
  breadcrumbList = [];

  onImageViewClick(values) {
    this.setState({
      modalImgVisible: true,
      modalImageValues: values,
    });
  }

  renderCountBox() {
    const { modelState: { loading: dataLoading, status: status, data, countData } } = this.props;
    const { showTotalCountBox, totalCountData } = this.state;
    //均分框数据展示组件 根据数据量的不同渲染不同的样式 按需添加

    let listItems = ''
    if (totalCountData && countData) {
      listItems = totalCountData.map((item, index) =>
        <div className={styles.countBoxCell} key={index}>
          <div className={styles.countBoxCellValue}>{item.before ? item.before + ' ' : ''}{countData[item.value]}</div>
          <div className={styles.countBoxCellLabel}>{item.label}</div>
        </div>
      );
    }
    return (
      showTotalCountBox && (
        <div>{ listItems }</div>
      )
    )
  }

  renderDataTable() {
    const { modelState: { loading: dataLoading, status: status, data, pagination } } = this.props;
    const { selectedRowKeys, selectedRows, tableColumns, tableScroll, expandedRowRender, tableBorder, showTableHeader,
      needTableColumnsOperator, needTableCheckbox, defaultExpandAllRows } = this.state;

    let columns = [];
    for (let col of tableColumns) {
      let colWrap = {};
      if (col.type) {
        switch (col.type) {
          case 'longString':
            colWrap = {
              render: (text, record) =>
                text ?
                  (
                    // -webkit-transition: all 3s;
                    <Tooltip title={text}>
                      <div style={{
                        transition: 'all .3s',
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', width: (col.width - 24) + 'px'
                      }}
                        onDoubleClick={(e) => {
                          if (e.target.style.textOverflow) {
                            e.target.style.overflow = null;
                            e.target.style.textOverflow = null;
                            e.target.style.whiteSpace = null;
                            // 强制让此组件重新渲染，控制固定列的高度变化
                            this.forceUpdate(() => { });
                          } else {
                            e.target.style.overflow = 'hidden';
                            e.target.style.textOverflow = 'ellipsis';
                            e.target.style.whiteSpace = 'nowrap';
                            this.forceUpdate(() => { });
                          }
                        }}
                      >
                        {text}
                      </div>
                    </Tooltip>
                  )
                  :
                  <span style={{ color: '#e8e8e8' }}> / </span>
            };
            break;
          case 'image':
            colWrap = {
              className: styles.nopadding,
              render: (text, record) =>
                (text || record[col.dataIndex]) ?
                  (
                    Array.isArray(record[col.dataIndex]) ?
                      <a style={{ textDecoration: 'underline', fontWeight: 'bold' }}
                        onClick={() => {
                          let values = [];
                          for (let i of record[col.dataIndex]) {
                            values.push({ title: i[col.imgTitle], src: i[col.imgSrc] });
                          }
                          this.onImageViewClick(values);
                        }} >查 看</a>
                      :
                      <img style={{ width: 60, height: 60, cursor: 'pointer', margin: 6, }} src={record[col.dataIndex]}
                        onClick={() => {
                          let values = [];
                          values.push({ title: col.dataIndex, src: record[col.dataIndex] });
                          this.onImageViewClick(values)
                        }} />
                  )
                  :
                  <span style={{ color: '#e8e8e8' }}> / </span>
            };
            break;
          default:
            break;
        }
      } else {
        colWrap = {
          render: (text, record) =>
            text != undefined && text != null ?
              <span>{text}</span>
              :
              <span style={{ color: '#e8e8e8' }}> / </span>
        };
      }
      colWrap = { ...colWrap, ...col };
      columns.push(colWrap);
    }

    let scrollX = null;
    let scrollY = null;
    if (tableScroll) {
      if (tableScroll.x) {
        scrollX = tableScroll.x;
      }

      if (tableScroll.y) {
        scrollY = tableScroll.y;
      }
    }

    if (!scrollX) {
      scrollX = 0;
      for (let c of columns) {
        scrollX = scrollX + (c.width ? c.width : 0);
      }
    }

    if (!scrollY) {
      scrollY = 800;
    }

    scrollY = window.innerHeight - 350;

    scrollX = scrollX + 300;

    if (!!needTableColumnsOperator) {
      columns.push(
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 100,
          render: (text, record) => (
            <div >
              <Tooltip title="编 辑">
                <a onClick={() => {
                  this.setState({ editedEntity: record });
                  this.handleOperator(true, '编辑', this.simpleEditForm, this.handleSimpleEditEvent, this.renderSimpleEditForm, null, null);
                }}>
                  <Icon type="edit" />
                </a>
              </Tooltip>

              <Divider type="vertical" />

              <Tooltip title="删 除">
                <a onClick={() => {
                  this.renderNeedConfirmOperatorModal({
                    needConfirm: true,
                    confirmTitle: '确定删除？',
                    confirmContent: '',
                    handleEvent: () => this.handleDeleteEvent(record),
                    okType: 'danger',
                    okText: "确认",
                    cancelText: "取消",
                  });
                }}>
                  <Icon type="delete" />
                </a>
              </Tooltip>

            </div>
          ),
        }
      );
    }

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: !!record.checkDisabled,
      }),
      fixed: expandedRowRender ? false : true,
    };

    return (
      <Table
        scroll={{ x: scrollX, y: scrollY }}
        loading={dataLoading}

        dataSource={data}
        columns={columns}

        rowKey={record => record.key}
        rowSelection={needTableCheckbox ? rowSelection : null}

        pagination={paginationProps}
        onChange={this.handleTableChange}

        bordered={tableBorder ? tableBorder : false}
        defaultExpandAllRows={defaultExpandAllRows}
        expandedRowRender={expandedRowRender}
        showHeader={showTableHeader}

      />
    );
  }

  render() {
    const { modelState: { status: status, data, pagination, operatorLoading ,statisticsData,loading} } = this.props;
    const { selectedRowKeys, selectedRows, modalVisible, modalTitle, modalWidth, editedEntity, tableColumns, tableScroll
      , needAdd, needEdit, needDelete, needSearch, needTableAlert, modalImgVisible,
      modalImageValues, searchFormItem, entityStatus,needTableStatistics, needFooterBtn, footerBtnConfig, needSwtichBtn, swtichBtnConfig, orderNum, orderAmount } = this.state;

    return (
      <PageHeaderLayout title="" className={styles.totalPageLayout} breadcrumbList={this.breadcrumbList}>
        {
          // 判断是否有操作按钮（需要改）
          ((needAdd && (this.state.addAuth ? hasAuthority(this.state.addAuth) : true))
            || (needEdit && (this.state.editAuth ? hasAuthority(this.state.editAuth) : true))
            || (needDelete && (this.state.deleteAuth ? hasAuthority(this.state.deleteAuth) : true))
            || (this._operator.filter(o => this.renderOperator(o) != null) != null
              && this._operator.filter(o => this.renderOperator(o) != null).length > 0 && this._operator)
            || (this._operatorBefore.filter(o => this.renderOperator(o) != null) != null
              && this._operatorBefore.filter(o => this.renderOperator(o) != null).length > 0)) && (
            <Card bordered={false} className={styles.shuyunOperatorPanel} >
              <div className={styles.tableListOperator}>
                {
                  this._operatorBefore.map(o => this.renderOperator(o))
                }
                {
                  needAdd && (this.state.addAuth ? hasAuthority(this.state.addAuth) : true) &&
                  (
                    <Button className={styles.tableListBasicOperatorBtn} icon="plus-square-o" type="dashed"
                      onClick={() => this.handleOperator(true, '新增', this.simpleAddForm, this.handleSimpleAddEvent, this.renderSimpleAddForm, null, null)}>
                      新 增
                    </Button>
                  )
                }
                {
                  needEdit && (this.state.editAuth ? hasAuthority(this.state.editAuth) : true) &&
                  (
                    <Button className={styles.tableListBasicOperatorBtn} icon="edit" type="" disabled={selectedRows.length != 1}
                      onClick={() => this.handleOperator(true, '编辑', this.simpleEditForm, this.handleSimpleEditEvent, this.renderSimpleEditForm, null, null)}>
                      编 辑
                    </Button>
                  )
                }
                {
                  needDelete && (this.state.deleteAuth ? hasAuthority(this.state.deleteAuth) : true) &&
                  (
                    <Button className={styles.tableListBasicOperatorBtn} icon="delete" type="danger"
                      disabled={this.state.deleteDisable ?
                        this.state.deleteDisable(selectedRows)
                        :
                        (selectedRows.length <= 0)}
                      onClick={() => this.renderNeedConfirmOperatorModal({
                        needConfirm: true,
                        confirmTitle: '确定删除？',
                        confirmContent: '',
                        handleEvent: () => this.handleDeleteEvent(),
                        okType: 'danger',
                        okText: "确认",
                        cancelText: "取消",
                      })}
                    >
                      删 除
                    </Button>
                  )
                }
                {
                  this._operator.map(o => this.renderOperator(o))
                }
                {/*
                  <Button className={styles.tableListOperatorBtn} icon="save" type=""
                  onClick={() => { console.log(this.state.selectedRows); console.log(this.state.editedEntity); }}
                  >
                  操作1
                  </Button>
                  <Button className={styles.tableListOperatorBtn} icon="save" type="" >操作2</Button>
                  <Button className={styles.tableListOperatorBtn} icon="save" type="" >操作3</Button>
                  <Button className={styles.tableListOperatorBtn} icon="save" type="" >操作4</Button>
                  <Button className={styles.tableListOperatorBtn} icon="save" type="" >操作5</Button>
                  <Button className={styles.tableListOperatorBtn} icon="save" type="" >操作6</Button>
                */}
              </div>
            </Card>
          )
        }

        {
          entityStatus && entityStatus.length > 1 && (
            <Card bordered={false} className={styles.shuyunStatusPanel} >
              <div className={styles.tableListOperator}>
                <Tabs defaultActiveKey={JSON.stringify(entityStatus[0])} onChange={this.onEntityStatusTabChange}>
                  {entityStatus.map(entityStatus => <TabPane tab={entityStatus.name} key={JSON.stringify(entityStatus)}></TabPane>)}
                </Tabs>
              </div>
            </Card>
          )
        }

        <Card bordered={false} bodyStyle={{ padding: '12px 24px' }} >
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {
                searchFormItem && searchFormItem.length > 0 && (this.renderSearchForm())
              }
            </div>

            <div className={styles.orderTable}>

              {
                needTableAlert &&
                (
                  <div className={styles.tableAlert}
                  // style={{ display: selectedRowKeys.length > 0 ? 'block' : 'none', }}
                  >
                    <Alert
                      message={(
                        <div>
                          总笔数 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 件&nbsp;&nbsp;
                          {/* 总计 <span style={{ fontWeight: 600 }}>{totalCallNo}</span> 项 */}
                          <a onClick={this.cleanSelectedKeys} style={{ marginLeft: 24 }}>清空</a>
                        </div>
                      )}
                      type="info"
                      showIcon
                    />
                  </div>
                )
              }
              {
                // 原↓代码
                // <span style={{paddingRight:40}}>订单个数： {statisticsData.orderNum}个</span>
                // <span >订单总额：{statisticsData.orderAmount?statisticsData.orderAmount:0}元</span>
              }
              {
                needTableStatistics && !loading ?
                  <Alert
                    message={(
                      <div style={{textAlign:'right',fontWeight:600}}>
                        <span style={{paddingRight:40}}>订单个数： {orderNum}个</span>
                        <span >订单总额：{orderAmount}元</span>
                      </div>
                    )}
                    type="info"
                />
                  : ''
              }

              {this.renderCountBox()}

              {this.renderDataTable()}

              {
                needFooterBtn && !loading ?
                  <div style={{marginTop: -48, position: 'absolute'}}>
                    {
                      footerBtnConfig.map((o) => this.renderOperator(o))
                    }
                  </div>
                  : ''
              }

              {
                needSwtichBtn && swtichBtnConfig && hasAuthority(swtichBtnConfig.authority) && !loading ?
                  <div style={{top: -48, right: 20, position: 'absolute'}}>
                    <span>{ swtichBtnConfig.label } </span>
                    <Switch defaultChecked={swtichBtnConfig.checked} checkedChildren={swtichBtnConfig.onlabel} unCheckedChildren={swtichBtnConfig.offlabel} onChange={swtichBtnConfig.handleEvent} />
                  </div>
                  : ''
              }
            </div>

          </div>
        </Card>

        <Modal className={styles.modalForm}
          title={modalTitle}
          visible={modalVisible}
          onCancel={() => this.handleOperator()}
          // onOk={this.handleModalSubmit}
          width={modalWidth}
          destroyOnClose={true}
          // confirmLoading={operatorLoading}
          footer={this.state.currentModalFootButton}
        >
          {this.state.currentRenderForm()}
        </Modal>

        {
          this.state.otherModal && this.state.otherModal()
        }

        <SyCarouselImageModalComponent
          values={this.state.modalImageValues}
          visible={this.state.modalImgVisible}
          onCancel={() => {
            this.setState({
              modalImgVisible: !this.state.modalImgVisible,
              modalImageValues: [],
            });
          }}
        >
        </SyCarouselImageModalComponent>


      </PageHeaderLayout >

    );
  }

}

export default SyOrderTableComponent;
